package com.niubi.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.niubi.yygh.common.exception.YyghException;
import com.niubi.yygh.oss.service.FileService;
import com.niubi.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
  @Override
  public String upload(MultipartFile file) {
    String endpoint = ConstantPropertiesUtil.END_POINT;
    String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
    String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
    String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
    String objectName = file.getOriginalFilename();

    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    objectName = uuid+objectName;

    String dateValue = new DateTime().toString("yyyy/MM/dd");
    objectName = dateValue+"/"+objectName;
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
      InputStream inputStream = file.getInputStream();
      ossClient.putObject(bucketName,objectName,inputStream);
      String url = "http://"+bucketName+"."+endpoint+"/"+objectName;
      return url;
    } catch (Exception oe) {
      throw new YyghException(20001,"文件上传失败");
    } finally {
      if (ossClient != null) {
        ossClient.shutdown();
      }
    }
  }
}
